#!/bin/bash -e

# Provide source directive to shellcheck.
# shellcheck source=meta-facebook/meta-greatlakes/recipes-phosphor/state/phosphor-state-manager/power-cmd
source /usr/libexec/phosphor-state-manager/power-cmd

SLOT_ID="$1"

function get_power_status()
{
        POWER_OK_SLOT=$(( $1+9 ))
        HOST_INSTANCE=$(( $1-1  << 2 ))

        chassis_status=$(gpioget 0 $POWER_OK_SLOT)
        if [ "$chassis_status" == "$STATE_OFF" ]; then
                echo "AC Off"
                return 0
        fi

        response="$(busctl call "$SERVICE" "$OBJECT_PATH" "$INTERFACE" sendRequest yyyyay "$HOST_INSTANCE" 0x38 "$LUN" 0x03 "$IANA_LEN" "$IANA")"
        # Responses are BIC gpio states, the GPIO B7 represents host DC status
        result=$(echo "$response" | cut -d" " -f "$PWRGD_SYS_PWROK_INDEX")
        res="$(( "$result" & 0x80  ))"
        host_status="$(( "$res" >> 7 ))"
        if [ "$host_status" == "$STATE_OFF" ]; then
                echo "Host Off"
                return 0
        fi
}

set_host_state()
{
        PROPERTY_VAL="xyz.openbmc_project.State.Host.HostState.$2"
        busctl set-property "$HOST_BUS_NAME$1" "$HOST_OBJ_PATH$1" "$HOST_INTF_NAME" "$HOST_PROPERTY_NAME" s "$PROPERTY_VAL"
}

set_chassis_state()
{
        PROPERTY_VAL="xyz.openbmc_project.State.Chassis.PowerState.$2"
        busctl set-property "$CHASSIS_BUS_NAME$1" "$CHASSIS_OBJ_PATH$1" "$CHASSIS_INTF_NAME" "$CHASSIS_PROPERTY_NAME" s "$PROPERTY_VAL"
}


POWER_STATUS=$(get_power_status "$SLOT_ID")

# Default power status
CHASSIS_STATE_VAL="Off"
HOST_STATE_VAL="Off"

# Real power status
if [ "$POWER_STATUS" != "AC Off" ]; then
    CHASSIS_STATE_VAL="On"
    if [ "$POWER_STATUS" != "Host Off" ]; then
        HOST_STATE_VAL="Running"
    fi
fi

set_chassis_state "$SLOT_ID" "$CHASSIS_STATE_VAL"
set_host_state "$SLOT_ID" "$HOST_STATE_VAL"
